﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Golos.Web.Utils
{
    public class TokenUtils
    {
        public const string COOKIE_KEY = "token";
        public const string SECRET_COOKIE_KEY = "x-fwd";
        public const string COOKIE_DOMAIN = "golosim.ru";
        
        public static Token FromCookies(HttpCookieCollection cookies)
        {
            HttpCookie requestTokenCookie = cookies[COOKIE_KEY];
            if (requestTokenCookie == null || string.IsNullOrEmpty(requestTokenCookie.Value))
            {
                //LogClass.WriteDebugEntry("Пришел пользователь с пустой кукой.");
                return null;
            }
            string token = null;
            try
            {
                token = Encrypter.DecryptString(requestTokenCookie.Value);
            }
            catch (Exception e)
            {
                LogClass.WriteDebugEntry("Удаляю куку [" + requestTokenCookie.Value + "], т.к. не могу расшифровать токен " + token);
                cookies.Remove(COOKIE_KEY);
                LogClass.WriteDebugEntry(e.ToString());
            }

            if (token == null)
                return null;

            return Token.Deserialize(token);
        }

        public static void ToCookies(HttpCookieCollection cookies, Token token)
        {
            string encryptedToken = Encrypter.EncryptString(token.Serialize());
            HttpCookie tokenCook = new HttpCookie(COOKIE_KEY, encryptedToken);
            
            tokenCook.Expires = DateTime.Now.AddDays(Settings.ReadFromFile().CookieLifeTime);
            tokenCook.Domain = COOKIE_DOMAIN;
            
            cookies.Add(tokenCook);

            // Write secret cookie

            string encryptedSecretCookie = Encrypter.EncryptString(token.Serialize());
            HttpCookie secretCook = new HttpCookie(SECRET_COOKIE_KEY, encryptedSecretCookie);

            secretCook.Expires = DateTime.Now.AddDays(Settings.ReadFromFile().CookieLifeTime + 10);
            secretCook.Domain = "gol.ru";

            cookies.Add(secretCook);
        }

        public static Token CheckSecretCookie(HttpCookieCollection cookies)
        {
            HttpCookie requestSecretCookie = cookies[SECRET_COOKIE_KEY];

            if (requestSecretCookie == null || string.IsNullOrEmpty(requestSecretCookie.Value))
            {
                return null;
            }

            string token = null;
            try
            {
                token = Encrypter.DecryptString(requestSecretCookie.Value);
            }
            catch (Exception e)
            {
                LogClass.WriteDebugEntry("Удаляю секретную куку [" + requestSecretCookie.Value +
                                         "], т.к. не могу расшифровать токен " + token);
                cookies.Remove(SECRET_COOKIE_KEY);
                LogClass.WriteDebugEntry(e.ToString());
            }

            if (token == null)
                return null;

            LogClass.WriteInfoEntry("У пользователя найдена секретная кука. " + token.ToString());
            return Token.Deserialize(token);
        }
    }
}